package org.panxiong.openapi.model;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * 方法结果模型
 */
public class ResultModel extends FieldModel implements Serializable {

    // 内容类型
    private String contentType;

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    /**
     * 附加的更新方法, 因为设置 Content-Type 的方式多样，所以没办法准确拿到 Content-Type， 仅供参考
     */
    public ResultModel updateContentType(Class<?> cls, Method method) {
        ResponseBody responseBody = method.getAnnotation(ResponseBody.class);
        if (responseBody != null) {
            this.contentType = "application/json";
        } else {
            RestController restController = cls.getAnnotation(RestController.class);
            if (restController != null) {
                this.contentType = "application/json";
            }
            Controller controller = cls.getAnnotation(Controller.class);
            if (controller != null) {
                this.contentType = "text/html";
            }
            RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
            if (requestMapping != null && requestMapping.produces().length > 0) {
                this.contentType = requestMapping.produces()[0];
            }
            GetMapping getMapping = method.getAnnotation(GetMapping.class);
            if (getMapping != null && getMapping.produces().length > 0) {
                this.contentType = getMapping.produces()[0];
            }
            PostMapping postMapping = method.getAnnotation(PostMapping.class);
            if (postMapping != null && postMapping.produces().length > 0) {
                this.contentType = postMapping.produces()[0];
            }
            PutMapping putMapping = method.getAnnotation(PutMapping.class);
            if (putMapping != null && putMapping.produces().length > 0) {
                this.contentType = putMapping.produces()[0];
            }
            PatchMapping patchMapping = method.getAnnotation(PatchMapping.class);
            if (patchMapping != null && patchMapping.produces().length > 0) {
                this.contentType = patchMapping.produces()[0];
            }
            DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);
            if (deleteMapping != null && deleteMapping.produces().length > 0) {
                this.contentType = deleteMapping.produces()[0];
            }
        }
        return this;
    }
}
